package com.link.play.fit.ai.utils

import android.content.Context
import com.link.play.fit.ai.R
import com.link.play.fit.ai.ext.d
import java.text.ParseException
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Calendar
import java.util.Date
import java.util.Locale




object WeekDatesUtil {
    fun getDayOfWeek(): Int {
        // 获取当前日期
        val today = LocalDate.now()
        // 获取本周的第几天（1 = 星期一, 7 = 星期日）
        return today.dayOfWeek.value
    }

    fun getLastSevenDaysPrefixes(): List<String> {
        val prefixes = mutableListOf<String>()
        val today = LocalDate.now()

        // 遍历今天到前七天
        for (i in 0 until 7) {
            val date = today.minusDays(i.toLong())
            val dayOfWeek = date.dayOfWeek
            val prefix = dayOfWeek.name.first().toString() // 获取星期的第一个字母
            prefixes.add(prefix)
        }
        prefixes.reverse()
        return prefixes
    }

    fun getFirstLetterOfWeek(dateString: String?): Char {
        try {
            val dateFormat: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
            val date: Date? = dateFormat.parse(dateString)

            val weekFormat: SimpleDateFormat = SimpleDateFormat("E", Locale.US)
            val weekDay: String = weekFormat.format(date)

            return weekDay[0]
        } catch (e: ParseException) {
            e.printStackTrace()
            return ' ' // 可根据需求处理异常情况
        }
    }
    fun getWeekday(dateStr: String,context: Context): String {
        return try {
            val currentDate = LocalDate.now()
            val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
            val currentFormat = currentDate.format(formatter)
            if(dateStr == currentFormat) {

                context.getString(R.string.today)
            }
            // 1. 解析日期字符串
            val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            val date = dateFormat.parse(dateStr)



            // 2. 使用 Calendar 获取星期几
            val calendar = Calendar.getInstance().apply { time = date }

            when (calendar.get(Calendar.DAY_OF_WEEK)) {
                Calendar.MONDAY -> context.getString(R.string.Monday)
                Calendar.TUESDAY -> context.getString(R.string.Tuesday)
                Calendar.WEDNESDAY -> context.getString(R.string.Wednesday)
                Calendar.THURSDAY -> context.getString(R.string.Thursday)
                Calendar.FRIDAY -> context.getString(R.string.Friday)
                Calendar.SATURDAY -> context.getString(R.string.Saturday)
                Calendar.SUNDAY -> context.getString(R.string.Sunday)
                else -> "?"
            }
        } catch (e: Exception) {
            "?" // 日期格式错误时返回占位符
        }
    }



    fun getWeekDatesAndShortWeekdays(
        date: Date = Date(),
        startFromMonday: Boolean = true
    ): Pair<List<String>, List<String>> {
        val calendar = Calendar.getInstance().apply {
            time = date
            firstDayOfWeek = if (startFromMonday) Calendar.MONDAY else Calendar.SUNDAY
        }

        // 调整到本周第一天
        calendar.set(Calendar.DAY_OF_WEEK, calendar.firstDayOfWeek)

        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val weekDays = mutableListOf<String>()
        val weekInitials = mutableListOf<String>()

        repeat(7) {
            weekDays.add(dateFormat.format(calendar.time))
            weekInitials.add(getWeekdayInitial(calendar))
            calendar.add(Calendar.DAY_OF_MONTH, 1)
        }

        return Pair(weekDays, weekInitials)
    }

    /**
     * 获取星期首字母（英文：M/T/W/T/F/S/S）
     */
    private fun getWeekdayInitial(calendar: Calendar): String {
        return when (calendar.get(Calendar.DAY_OF_WEEK)) {
            Calendar.MONDAY -> "M"
            Calendar.TUESDAY -> "T"
            Calendar.WEDNESDAY -> "W"
            Calendar.THURSDAY -> "T"
            Calendar.FRIDAY -> "F"
            Calendar.SATURDAY -> "S"
            Calendar.SUNDAY -> "S"
            else -> ""
        }
    }

    /**
     * 计算距离下一个周一 15:00 的延迟时间（毫秒）
     */
    fun getNextMondayDelay(): Long {
        val calendar = Calendar.getInstance().apply {
            // 设置目标时间：周一 15:00
            set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
            set(Calendar.HOUR_OF_DAY, 15)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)

            // 如果当前时间已过本周一 15:00，则计算下周一的同一时间
            if (timeInMillis <= System.currentTimeMillis()) {
                add(Calendar.WEEK_OF_YEAR, 1)
            }
        }
        return calendar.timeInMillis - System.currentTimeMillis()
    }

    fun getCurrentLanguage(context: Context): String {
        val prefs = context.getSharedPreferences("Settings", Context.MODE_PRIVATE)
        return prefs.getString("app_language", Locale.getDefault().language) ?: "en"
    }

}